package com.syyo.admin.service.impl;

import com.alibaba.excel.EasyExcel;
import com.syyo.admin.common.constant.SettingsConstant;
import com.syyo.admin.common.enums.ResultEnum;
import com.syyo.admin.common.exception.SysException;
import com.syyo.admin.domain.FileUpload;
import com.syyo.admin.domain.ResultVo;
import com.syyo.admin.domain.entity.SysUser;
import com.syyo.admin.domain.excel.UserExport;
import com.syyo.admin.mapper.SysUserMapper;
import com.syyo.admin.service.FileService;
import com.syyo.admin.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Auther: wangzhong
 * @Date: 2020/8/18 10:17
 * @Description:
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private SettingsConstant settingsConstant;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResultVo<FileUpload> uploadFile(MultipartFile file) {
        FileUpload fileUpdate = new FileUpload();
        // 获取文件名称
        String encoderFilename = file.getOriginalFilename();

        // 计算文件大小
        long fileS = file.getSize();
        String fileSizeString = MyFileUtil.FormetFileSize(fileS);

        //url解码
        String decoderFilename = MyurlUtils.getURLDecoderString(encoderFilename);

        // 文件后缀名
        //判断文件类型，获取不同的文件存储路径
        String filePath = isFileType(decoderFilename);
        String suffix = decoderFilename.substring(decoderFilename.lastIndexOf("."));
        //uuid去除中间的 '-'
        String uuid = UUID.randomUUID().toString().replace("-","");
        String fileFullName = filePath + uuid + suffix;
        File dest = new File(fileFullName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try{
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        fileUpdate.setFileName(decoderFilename);
        fileUpdate.setUrl(fileFullName);
        fileUpdate.setFileSize(fileSizeString);
        return ResultUtils.ok(fileUpdate);
    }

    /**
     * 文件下载
     * @param fileName
     * @param uuid
     * @param response
     * @throws IOException
     */
    @Override
    public void downloadFile(String fileName, String uuid,HttpServletResponse response) throws IOException {
        ValueOperations<String, String> redis = redisTemplate.opsForValue();
        String userFile = redis.get(uuid);
        if (MyStringUtils.isEmpty(userFile)){
            throw new SysException(ResultEnum.E_90004.getCode(), ResultEnum.E_90004.getMessage());
        }
        if("user".equals(fileName)){
            // 导出用户数据
            exportUser(response);
            redisTemplate.delete(uuid);
        }
    }

    /**
     * 导出用户数据
     * @param response
     * @throws IOException
     */
    private void exportUser(HttpServletResponse response) throws IOException {
        List<SysUser> sysUsers = userMapper.selectList(null);
        List<UserExport> list = new ArrayList<>();
        for (SysUser sysUser : sysUsers) {
            UserExport userExport1 = new UserExport();
            userExport1.setUserName(sysUser.getUserName());
            userExport1.setNickName(sysUser.getNickName());
            userExport1.setEmail(sysUser.getEmail());
            userExport1.setPhone(sysUser.getPhone());
            list.add(userExport1);
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String dateStr = "user_" + MyDateUtils.getDateStr();
        response.setHeader("Content-disposition", "attachment;filename=" + dateStr + ".xlsx");
        // 这里需要设置不关闭流
        EasyExcel.write(response.getOutputStream(), UserExport.class)
                .autoCloseStream(Boolean.FALSE).sheet("sheet").doWrite(list);
    }

    /**
     * 判断文件类型 ,1：图片，2：文档，3：音乐，4：视频，5：其他
     * @param fileName
     * @return
     */
    private String isFileType(String fileName) {
        String filePath = null;
        int fileType = MyFileUtil.getFileType(fileName);
        switch(fileType){
            case 1: return settingsConstant.getImagePath();
            case 2: return settingsConstant.getDocumentsPath();
            case 3: return settingsConstant.getMusicPath();
            case 4: return settingsConstant.getVideoPath();
            default: return settingsConstant.getOtherPath();
        }
    }
}
